<?php
namespace app\erp\model;

use think\Model;
use think\Cache;

class PriceRecorddb extends Model
{

    protected $name = 'price_record';

    protected $type = [
        'create_time' => 'timestamp:Y-m-d H:i'
    ];
    // 自动完成时间转换
    protected $autoWriteTimestamp = true;

    public $param = array();

    protected function cache_name($name)
    {
        $new_arr = $this->param;
        $new_arr['partner_id'] = PARTNER_ID;
        if (! isset($new_arr['site_id'])) {
            $new_arr['site_id'] = SITE_ID;
        }
        ksort($new_arr);
        $param_str = http_build_query($new_arr);
        return md5($name . $param_str);
    }

    public function scopeSiteId($query, $site_id)
    {
        if ($site_id) {
            $query->where('site_id', $site_id);
        } else {
            $query->where('site_id', null);
        }
    }

    public function scopeGoodsSku($query, $goods_sku)
    {
        $query->where('goods_sku', $goods_sku);
    }

    public function base($query)
    {
        if (isset($this->param['site_id'])) {
            $query->siteId($this->param['site_id']);
        }
        if (isset($this->param['goods_sku'])) {
            $query->goodsSku($this->param['goods_sku']);
        }
    }

    public function ajaxSave()
    {
        $this->param['create_time'] = time();
        $chk_find = $this->ajaxFind();
        if (count($chk_find) == 0) {
            $this->allowField(true)->insert($this->param);
        } else {
            if (($chk_find['sale_price'] != $this->param['sale_price']) || ($chk_find['market_price'] != $this->param['market_price']) || ($this->param['api_price'] != $chk_find['api_price'])) {
                $this->allowField(true)->insert($this->param);
            }
        }
        Cache::clear('price_record');
        return 'success';
    }

    public function ajaxSelect()
    {
        if (! isset($this->param['get_price_type'])) {
            $this->param['get_price_type'] = 'sale_price';
        }
        $price_field = str_replace('get_', '', $this->param['get_price_type']);
        $data = $this->field('max(create_time) create_time,' . $price_field . ' price,goods_sku')
            ->limit('0,100')
            ->order('create_time asc')
            ->group($price_field)
            ->cache($this->cache_name('price_record_select'), 86400, 'price_record')
            ->select();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }

    public function ajaxFind()
    {
        $data = $this->find();
        if ($data) {
            $data = $data->toArray();
        } else {
            $data = array();
        }
        return $data;
    }
}